package cpa.prowon.image;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import cpa.prowon.Application;
import cpa.prowon.gui.MainWindow;

/**
 * This class is used to create thumbnails from an ImageContainer
 * @author Chris
 */
public class Thumbnail {

	// Properties
	private ImageContainer ic;
	private Image _image;
	
	/**
	 * Create a new thumbnail
	 * @param ImageContainer The image container which holds the reference to the actual physical image
	 * @author Chris
	 */
	public Thumbnail (ImageContainer input_image) {
		ic = input_image;
	}

	/**
	 * Create the thumbnail for the given image container
	 * @param ImageContainer The actual image container to use
	 * @author Chris
	 */
	public void createThumbnail(ImageContainer input_image) {

		// Try opening the file, if it doesn't exist anymore, return		
		File f = new File(input_image.getPathName());
		if (!f.exists()) {
			return;
		}

		// Create the image reader
		ImageInputStream iis = null;
		try {
			iis = ImageIO.createImageInputStream(f);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Iterator readers = ImageIO.getImageReaders(iis);
		ImageReader reader = (ImageReader) readers.next();
		reader.setInput(iis, true);
			
		// Calculate the scaling factor
		int maxSize = (new Integer(Application.getInstance().getApplicationProperties().getProperty(MainWindow.PROPNAME_THUMBNAILSIZE))).intValue();
		int curr_height = 0;
		int curr_width = 0;
		try {
			curr_height = reader.getHeight(0);
			curr_width = reader.getWidth(0);
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		int scale_factor = curr_width / maxSize;
		if (scale_factor == 0) {
			scale_factor = 1;
		} 
		int newHeight = curr_height / scale_factor;
		if (newHeight > maxSize) {
			scale_factor = curr_height / maxSize;
		}
			
		// Create the reader parameters
		ImageReadParam param = reader.getDefaultReadParam();
		param.setSourceSubsampling(scale_factor, scale_factor, 0,0);
		
		// Get the buffered image
		BufferedImage image = null;
		try {
			image = reader.read(0, param);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		// Save the image		
		float quality = (float) 1;
		saveJPG(image, quality, "tmp.jpg");
			
		// Create the image and return it
		Display display = Display.getCurrent();
		_image = new Image(display, "tmp.jpg");

		// Close the file
		try {
			iis.close();
		} catch (IOException e) {
			System.out.println(e);
		}

	}

	/**
	 * Save the JPG file
	 * @param BufferedImage The buffered image to be used
	 * @param float The quality in which the JPG shall be saved
	 * @param String The path name under which the picture shall be saved
	 * @author Chris
	 */
	public void saveJPG(BufferedImage bi, float q, String pathname){
		
		// Create the file output stream
		String s = null;
		FileOutputStream out = null;
		try {
			File file = new File(pathname);
			s = file.getName();
			out = new FileOutputStream(file);
		} catch (java.io.FileNotFoundException io){
			System.out.println("File Not Found");
		}
		
		// Create the image encoder and its parameters
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
		param.setQuality(q, false);
		try {
			encoder.encode(bi, param);
		} catch (java.io.IOException io) {
			System.out.println("IOException");
		}
		try{
			out.close();
		} catch (java.io.IOException io){
			System.out.println("IOException");
		}
	
	}

	/**
	 * Return the image, if it's not yet created, create it
	 * @return The actual thumbnail as SWT image
	 * @author Chris
	 */
	public Image getImage() {
		if (_image == null) {
			createThumbnail(ic);
		}
		return _image;
	}

}
